package com.joysuch.wwyt.api.mh.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.mh.enums.MonitPointSendType;
import com.joysuch.wwyt.api.mh.service.MonitPointConfigService;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MhMonitPointRestSender {

    //最近一次发送时间 ms :毫秒
    private static Long LAST_JOB_TIME = null;

     @Autowired
     private BaseConfigService baseConfigService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MonitPointConfigService monitPointConfigService;

    private static final String DATE_FORMAT_COLLECT_TIME = "yyyy-MM-dd HH:mm:ss";

    private static final DateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT_COLLECT_TIME);

    private static Map<String,JSONObject>  monitPointMap =  new ConcurrentHashMap<>();
    private static Map<String,Double>  monitPointHistoryMap =  new ConcurrentHashMap<>();


    public void sendMessage(List<MonitorPointData> list) {

        if(list == null){
            log.debug("... mh rest sender: monitor point list is null, no data to send out.");
            return;
        }
        // 获取监测点配置列表
        RMap<String, String> configMap = monitPointConfigService.getMointPointConfigMap(MonitPointSendType.REST.getCode());
        String config[] = null;

        for(MonitorPointData point: list){
            if(configMap.containsKey(point.getPointCode())) {
                config = configMap.get(point.getPointCode()).split(",");
                JSONObject obj = new JSONObject();
                obj.put("CGQBH", config[0]);
                obj.put("CJSJ", simpleDateFormat.format(new Date()));
                //如果当前监测点值为0， 则取最近一次非0值
//                if(point.getValue().equals(0) && monitPointHistoryMap.containsKey(point.getPointCode())){
//                    obj.put("VALUE", monitPointHistoryMap.get(point.getPointCode()) * Double.valueOf(config[1]));
//                }else {
                    obj.put("VALUE", String.format("%.2f",(point.getValue() * Double.valueOf(config[1]))));
                    monitPointHistoryMap.put(obj.get("CGQBH").toString(), point.getValue());
//                }
                monitPointMap.put(point.getPointCode(), obj);
            }
        }

        Integer jobSendSchedule = 240000 ;
        // 间隔 JOB_SEND_SCHEDULE 时间发送信息
        if(LAST_JOB_TIME !=null && System.currentTimeMillis() - LAST_JOB_TIME < jobSendSchedule){
            log.info("... mh rest sender: post schedule not send ");
            return;
        }

        JSONArray array = new JSONArray();
        LAST_JOB_TIME = System.currentTimeMillis();
        Collection<JSONObject> dataList = monitPointMap.values();
        dataList.stream().forEach(item->array.add(item));

        //调用方法，发送数据
        restPostData(array);
        monitPointMap.clear();

    }


    /**
     * Http rest post out the data list
     * @param data
     */
    private void restPostData(JSONArray data){
       log.info("... mh rest sender: post request size: "+ data.size());
       if(data.size() ==0){
           return;
       }
        BaseConfig postUrlConfig =  baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_REST_URL);
        if(postUrlConfig== null){
            return ;
        }
        BaseConfig userNameConfig =  baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_REST_USER);
        BaseConfig passwordConfig =  baseConfigService.getBaseConfigFromRedis(SyncConstants.MH_MONITPOINT_API_REST_PWD);

        log.info("... mh rest sender: post request data: "+ data.toString());
        HttpHeaders header = new HttpHeaders();
        // 需求需要传参为form-data格式
        header.setContentType(MediaType.MULTIPART_FORM_DATA);
        header.set("username",userNameConfig == null ? "" : userNameConfig.getValue().trim());
        header.set("password",passwordConfig == null ? "" : passwordConfig.getValue().trim());

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("data", data.toJSONString());
        //HttpEntity
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, header);
        //post
        ResponseEntity<MhResponse> response = restTemplate.postForEntity(postUrlConfig.getValue().trim(), requestEntity, MhResponse.class);
        log.debug("... mh rest sender: post response: "+ response.getBody());

    }


}
